package cn.didi.feidi.androidorder.fragment;


import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;

import java.util.HashMap;
import java.util.Map;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.PersonServiceItemActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonAboutUsActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonAdviceCallBackActivity;
import cn.didi.feidi.androidorder.activity.personal.PersonInvitedByWaterDeliverActivity;
import cn.didi.feidi.androidorder.api.Api;
import cn.didi.feidi.androidorder.api.ApiResponse;
import cn.didi.feidi.androidorder.api.ErrorEvent;
import cn.didi.feidi.androidorder.assembly.AppSettingSelectUpdateWaysPopupWindow;
import cn.didi.feidi.androidorder.assembly.CommomDialog;
import cn.didi.feidi.androidorder.core.ActionCallbackListener;
import cn.didi.feidi.androidorder.core.AppActionRequest;
import cn.didi.feidi.androidorder.manager.AppManager;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.AppInfo;
import cn.didi.feidi.androidorder.model.UserAddress;
import cn.didi.feidi.androidorder.service.DownloadApkService;
import cn.didi.feidi.androidorder.util.GlideCacheUtil;
import cn.didi.feidi.androidorder.util.PackageUtil;

public class AppSettingFragment extends FeidiBaseFragment {


    private static final String TAG = "AppSettingFragment";
    AsyncSession asyncSession;
    private GlideCacheUtil glideCacheUtil = GlideCacheUtil.getInstance();
    private LinearLayout inviteByWaterDeliver;
    private TextView invitedWaterDeliverName;

    private LinearLayout autoDownloadUpdate;
    private LinearLayout checkUpdate;
    private LinearLayout cleanCache;
    private LinearLayout adviceCallBack;
    private LinearLayout serviceItems;
    private LinearLayout aboutUs;

    private TextView tvVersion;

    private TextView quitAccount;
    private TextView updateWays;
    private TextView cacheCapacity;
    //自定义的弹出框类
    private AppSettingSelectUpdateWaysPopupWindow menuWindow;
    //为弹出窗口实现监听类
    private OnClickListener itemsOnClick = new OnClickListener() {

        public void onClick(View v) {
            menuWindow.dismiss();
            switch (v.getId()) {
                case R.id.app_setting_only_wifi_Update:
                    updateWays.setText("仅WLAN环境下");
                    //  更新个人配置
                    AppManager.setAppDownloadApkMode(AppManager.APP_DOWNLOAD_APK_MODE_WIFI_ONLY);
                    break;
                case R.id.app_setting_forever_Update:
                    updateWays.setText("永远");
                    //  更新个人配置
                    AppManager.setAppDownloadApkMode(AppManager.APP_DOWNLOAD_APK_MODE_ALWAYS);
                    break;
                case R.id.app_setting_never_Update:
                    updateWays.setText("从不");
                    //  更新个人配置
                    AppManager.setAppDownloadApkMode(AppManager.APP_DOWNLOAD_APK_MODE_NEVER);
                    break;
                default:
                    break;
            }
        }

    };


    /**
     * 与activity关联，后面可考虑单例模式
     *
     * @param bundle
     * @return
     */
    public static AppSettingFragment newInstance(Bundle bundle) {
        AppSettingFragment fragment = new AppSettingFragment();
        if (bundle != null)
            fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_app_setting, container, false);
        Log.d(TAG, "initFragment");
        return rootView;
    }

    @Override
    protected void initViews(View rootView) {
        inviteByWaterDeliver = (LinearLayout) rootView.findViewById(R.id.app_setting_invited_by_water_deliver_ll);
        invitedWaterDeliverName = (TextView) rootView.findViewById(R.id.app_setting_invited_by_water_deliver_name_tv);

        autoDownloadUpdate = (LinearLayout) rootView.findViewById(R.id.app_setting_auto_download_update_ll);
        checkUpdate = (LinearLayout) rootView.findViewById(R.id.app_setting_check_update_ll);
        cleanCache = (LinearLayout) rootView.findViewById(R.id.app_setting_clean_cache_ll);
        adviceCallBack = (LinearLayout) rootView.findViewById(R.id.app_setting_advice_callBack_ll);
        serviceItems = (LinearLayout) rootView.findViewById(R.id.app_setting_service_items_ll);
        aboutUs = (LinearLayout) rootView.findViewById(R.id.app_setting_about_us_ll);

        tvVersion = (TextView) rootView.findViewById(R.id.app_setting_version);

        quitAccount = (TextView) rootView.findViewById(R.id.app_setting_quit_account_tv);

        updateWays = (TextView) rootView.findViewById(R.id.app_setting_update_ways_tv);
        cacheCapacity = (TextView) rootView.findViewById(R.id.app_setting_cache_capacity_tv);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserManager.isBingAccount()) {
            quitAccount.setVisibility(View.VISIBLE);
        } else {
            quitAccount.setVisibility(View.GONE);
        }

        if (UserManager.getWaterDelverId() == null || UserManager.getWaterDelverId().equals("")) {
            invitedWaterDeliverName.setText("未绑定");
        } else {
            invitedWaterDeliverName.setText("已绑定");
        }

        cacheCapacity.setText(glideCacheUtil.getCacheSize(OrderApplication.getContext()));
    }

    @Override
    protected void initData() {

        asyncSession = OrderApplication.getDaoSession().startAsyncSession();
        // 初始化 updateWays 和 cacheCapacity 的值
        AppInfo appInfo = AppManager.getAppInfo();

        if (PackageUtil.getVersionName(mActivity).compareTo(appInfo.getVersion()) < 0) {// 非强制更新提示
            tvVersion.setText(appInfo.getVersion());
            tvVersion.setTextColor(getResources().getColor(R.color.theme_background_red));
            tvVersion.setTypeface(Typeface.DEFAULT_BOLD);
        } else {
            tvVersion.setTextColor(getResources().getColor(R.color.label_text_color));
        }

        switch (AppManager.getAppDownloadApkMode()) {
            case AppManager.APP_DOWNLOAD_APK_MODE_WIFI_ONLY:
                updateWays.setText("仅WLAN环境下");
                break;
            case AppManager.APP_DOWNLOAD_APK_MODE_ALWAYS:
                updateWays.setText("永远");
                break;
            case AppManager.APP_DOWNLOAD_APK_MODE_NEVER:
                updateWays.setText("从不");
                break;
            default:
                break;
        }
    }

    @Override
    protected void addListener() {
        inviteByWaterDeliver.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("WaterDelverId", UserManager.getWaterDelverId());
                if (!UserManager.isBingAccount()) {
                    makeToast("请先登陆");
                } else if (UserManager.getWaterDelverId() == null || UserManager.getWaterDelverId().equals("")) {
                    Intent intent = new Intent(getContext(), PersonInvitedByWaterDeliverActivity.class);
                    startActivity(intent);
                } else {
                    makeToast("邀请人已绑定");
                }
            }
        });

        autoDownloadUpdate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                menuWindow = new AppSettingSelectUpdateWaysPopupWindow(getActivity(), itemsOnClick);
                //显示窗口
                menuWindow.showAtLocation(getView(), Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
                setOtherPlaceDark();
            }
        });
        checkUpdate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String version = PackageUtil.getVersionName(mActivity);
                Map<String, String> data = new HashMap<String, String>();
                data.put("version", version);
                executeRequest(new AppActionRequest<AppInfo>(Api.CHECK_APP_VERSION, data, new TypeToken<ApiResponse<AppInfo>>() {
                }.getType(), new ActionCallbackListener<AppInfo>() {
                    @Override
                    public void onSuccess(String message, AppInfo appInfo) {
                        AppManager.putAppInfo(appInfo);
                        String newVersion = appInfo.getVersion();

                        if (PackageUtil.getVersionName(mActivity).compareTo(newVersion) < 0) {// 非强制更新提示
                            tvVersion.setText(newVersion);
                            tvVersion.setTextColor(getResources().getColor(R.color.theme_background_red));
                            tvVersion.setTypeface(Typeface.DEFAULT_BOLD);
                            if (appInfo.isForce()) {
                                // 如果是强制更新,则自动下载，不进行提示
                                downloadAPK();
                                return;
                            } else {
                                showUpdateDialog(appInfo);
                            }
                        } else {
                            tvVersion.setTextColor(getResources().getColor(R.color.theme_background_deep_gray));
                        }
                    }

                    @Override
                    public void onFailure(int errorEvent, String message) {
                        makeToast(message);
                    }
                }));
            }
        });

        cleanCache.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                glideCacheUtil.clearImageAllCache(OrderApplication.getContext());
                makeToast("已清理缓存");
                cacheCapacity.setText(glideCacheUtil.getCacheSize(OrderApplication.getContext()));
            }
        });

        adviceCallBack.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonAdviceCallBackActivity.class);
                startActivity(intent);
            }
        });

        serviceItems.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonServiceItemActivity.class);
                startActivity(intent);
            }
        });

        aboutUs.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getContext(), PersonAboutUsActivity.class);
                startActivity(intent);
            }
        });

        quitAccount.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserManager.isBingAccount()) {
                    //  弹出提示框
                    new CommomDialog(getContext(), R.style.dialog, "确认退出登录", new CommomDialog.OnCloseListener() {
                        @Override
                        public void onClick(Dialog dialog, boolean confirm) {
                            if (confirm) {
                                goLogin();
                                dialog.dismiss();
                            } else {
                                dialog.dismiss();
                            }
                        }
                    }, false, true).setNegativeButton("取消").setPositiveButton("确认").show();
                } else {
                    makeToast("尚未登录");
                }
            }
        });
    }

    //    设置popupWindow 弹出时界面其它部分变透明
    private void setOtherPlaceDark() {
        WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
        //当弹出Popupwindow时，背景变半透明
        params.alpha = 0.7f;
        getActivity().getWindow().setAttributes(params);
        //设置Popupwindow关闭监听，当Popupwindow关闭，背景恢复1f
        menuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
                params.alpha = 1f;
                getActivity().getWindow().setAttributes(params);
            }
        });
    }

    /**
     * 提醒更新版本
     *
     * @param appInfo
     */
    private void showUpdateDialog(final AppInfo appInfo) {
        new CommomDialog(mActivity, R.style.dialog, appInfo.getClientDesc(), new CommomDialog.OnCloseListener() {
            @Override
            public void onClick(Dialog dialog, boolean confirm) {
                if (confirm) {
                    Log.d(TAG, "现在更新");
                    downloadAPK();
                    dialog.dismiss();
                } else {
                    Log.d(TAG, "待会更新");
                    dialog.dismiss();
                }
            }
        }, false, false).setTitle("版本更新").setNegativeButton("待会更新").setPositiveButton("现在更新").show();
    }

    private void downloadAPK() {
        mActivity.startService(new Intent(mActivity, DownloadApkService.class));
    }

    /**
     * 跳转到重启界面
     */
    private void goLogin() {
        Map<String, String> data = new HashMap<String, String>();
        data.put("userId", UserManager.getUserId());
        data.put("token", UserManager.getToken());

        executeRequest(new AppActionRequest<String>(Api.LOGOUT, data, new TypeToken<ApiResponse<String>>() {
        }.getType(), new ActionCallbackListener<String>() {
            @Override
            public void onSuccess(String message, String data) {
                Log.d(TAG, "REGISTER success: " + message);
                makeToast("退出登录成功");

                getFeidiHandler().closeService();
                UserManager.clearBingAccountInfo();
                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                    @Override
                    public void onAsyncOperationCompleted(AsyncOperation operation) {

                        if (operation.isFailed()) {
                            Log.d(TAG, "onAsyncOperationCompleted: " + operation.getThrowable().getMessage());
                        }

                    }
                });
                asyncSession.deleteAll(UserAddress.class);//清除当前用户保存在数据库的地址信息

                Intent i = getActivity().getPackageManager()
                        .getLaunchIntentForPackage(getActivity().getPackageName());
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(i);
                android.os.Process.killProcess(android.os.Process.myPid());
            }

            @Override
            public void onFailure(int errorEvent, String message) {
                Log.d(TAG, "REGISTER failure errorEvent: " + errorEvent + "message: " + message);
                switch (errorEvent) {
                    case ErrorEvent.ERROR_LOGOUT_NO_EXIST:
                        makeToast("不存在登录行为");
                        break;
                    default:
                        makeToast("退出登录失败");
                        break;
                }
                getFeidiHandler().closeService();
                UserManager.clearBingAccountInfo();
                asyncSession.setListenerMainThread(new AsyncOperationListener() {
                    @Override
                    public void onAsyncOperationCompleted(AsyncOperation operation) {

                        if (operation.isFailed()) {
                            Log.d(TAG, "onAsyncOperationCompleted: " + operation.getThrowable().getMessage());
                        }

                    }
                });
                asyncSession.deleteAll(UserAddress.class);//清除当前用户保存在数据库的地址信息

                Intent i = getActivity().getPackageManager()
                        .getLaunchIntentForPackage(getActivity().getPackageName());
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(i);
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }));

    }
}
